<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>管理员后台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-danger">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">医院管理系统</a>
            <span class="navbar-text">欢迎, {{ username }}</span>
        </div>
    </nav>
    <main class="container mt-4">
        <h1 class="mb-4">管理员后台</h1>

        <!-- 医生管理 -->
        <div class="card mb-4">
            <div class="card-header"><h4>医生管理</h4></div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead><tr><th>工号</th><th>姓名</th><th>所属科室</th><th>职称</th></tr></thead>
                    <tbody id="doctors-table-body"></tbody>
                </table>
                <hr>
                <h5>添加新医生</h5>
                <form id="add-doctor-form" class="row g-3">
                    <div class="col-md-3"><input type="text" id="doc-id" class="form-control" placeholder="工号" required pattern="^doc.*"></div>
                    <div class="col-md-3"><input type="text" id="doc-name" class="form-control" placeholder="姓名" required></div>
                    <div class="col-md-3"><select id="doc-dept" class="form-select" required></select></div>
                    <div class="col-md-3"><input type="password" id="doc-pass" class="form-control" placeholder="初始密码" required></div>
                    <div class="col-md-4"><input type="text" id="doc-title" class="form-control" placeholder="职称" required></div>
                    <div class="col-12"><button type="submit" class="btn btn-success">添加医生</button></div>
                </form>
            </div>
        </div>

        <!-- 病人管理 (类似结构) -->
        <div class="card">
            <div class="card-header"><h4>病人管理</h4></div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead><tr><th>病历号</th><th>姓名</th><th>性别</th><th>电话号码</th></tr></thead>
                    <tbody id="patients-table-body"></tbody>
                </table>
                <hr>
                <h5>添加新病人</h5>
                <form id="add-patient-form" class="row g-3">
                    <div class="col-md-3"><input type="text" id="pat-id" class="form-control" placeholder="病历号" required pattern="^pat.*"></div>
                    <div class="col-md-3"><input type="text" id="pat-name" class="form-control" placeholder="姓名" required></div>
                    <div class="col-md-2"><select id="pat-gender" class="form-select"><option value="M">男</option><option value="F">女</option></select></div>
                    <div class="col-md-4"><input type="password" id="pat-pass" class="form-control" placeholder="初始密码" required></div>
                    <div class="col-md-4"><input type="text" id="pat-phone" class="form-control" placeholder="电话号码" required></div>
                    <div class="col-12"><button type="submit" class="btn btn-primary">添加病人</button></div>
                </form>
            </div>
        </div>

        <!-- 活跃预约管理 -->
        <div class="card mt-4">
            <div class="card-header"><h4>活跃预约</h4></div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>预约ID</th>
                            <th>预约日期</th>
                            <th>状态</th>
                            <th>病人信息</th>
                            <th>医生信息</th>
                            <th>科室</th>
                        </tr>
                    </thead>
                    <tbody id="active-appointments-table-body"></tbody>
                </table>
            </div>
        </div>

        <!-- 新增：科室概况 -->
        <div class="card mt-4">
            <div class="card-header"><h4>科室概况</h4></div>
            <div class="card-body">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>科室名称</th>
                            <th>医生数量</th>
                            <th>活跃预约数</th>
                        </tr>
                    </thead>
                    <tbody id="department-stats-body">
                        <!-- 数据将在这里动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 新增：总体概览 -->
        <div class="card mt-4">
            <div class="card-header"><h4>总体概览</h4></div>
            <div class="card-body">
                <ul class="list-group list-group-flush" id="overall-stats-list">
                    <!-- 数据将在这里动态加载 -->
                </ul>
            </div>
        </div>

    </main>
<script>
document.addEventListener('DOMContentLoaded', () => {
    // 加载所有数据
    fetchAndRenderDoctors();
    fetchAndRenderPatients();
    fetchAndRenderDepartments();
    fetchAndRenderActiveAppointments();
    fetchAndRenderDepartmentStats();
    fetchAndRenderOverallStats(); // 新增：调用总体概览加载函数

    // 绑定表单提交事件
    document.getElementById('add-doctor-form').addEventListener('submit', handleAddDoctor);
    document.getElementById('add-patient-form').addEventListener('submit', handleAddPatient);
});

// 加载并渲染医生列表
async function fetchAndRenderDoctors() {
    const response = await fetch('/api/doctors/');
    const doctors = await response.json();
    const tableBody = document.getElementById('doctors-table-body');
    tableBody.innerHTML = doctors.map(doc => `
        <tr><td>${doc.id}</td><td>${doc.name}</td><td>${doc.department.name}</td><td>${doc.title || ''}</td></tr>
    `).join('');
}

// 加载并渲染病人列表
async function fetchAndRenderPatients() {
    const response = await fetch('/api/patients/');
    const patients = await response.json();
    const tableBody = document.getElementById('patients-table-body');
    tableBody.innerHTML = patients.map(pat => `
        <tr><td>${pat.id}</td><td>${pat.name}</td><td>${pat.gender === 'M' ? '男' : '女'}</td><td>${pat.phone_number || ''}</td></tr>
    `).join('');
}

// 加载科室到下拉菜单
async function fetchAndRenderDepartments() {
    const response = await fetch('/api/departments/');
    const departments = await response.json();
    const selectEl = document.getElementById('doc-dept');
    selectEl.innerHTML = departments.map(dept => `<option value="${dept.id}">${dept.name}</option>`).join('');
}

// 新增：加载并渲染活跃预约列表
async function fetchAndRenderActiveAppointments() {
    const response = await fetch('/api/active_appointments/');
    const appointments = await response.json();
    const tableBody = document.getElementById('active-appointments-table-body');
    tableBody.innerHTML = appointments.map(appt => `
        <tr>
            <td>${appt.appointment_id}</td>
            <td>${appt.appointment_date}</td>
            <td>${appt.status}</td>
            <td>${appt.patient_id} - ${appt.patient_name} (${appt.patient_phone_number || '无'})</td>
            <td>${appt.doctor_id} - ${appt.doctor_name} (${appt.doctor_title || '无'})</td>
            <td>${appt.department_name}</td>
        </tr>
    `).join('');
}

// 新增：加载并渲染科室概况
async function fetchAndRenderDepartmentStats() {
    const response = await fetch('/api/dashboard/department_stats/');
    const stats = await response.json();
    const tableBody = document.getElementById('department-stats-body');
    tableBody.innerHTML = stats.map(stat => `
        <tr>
            <td>${stat.department_name}</td>
            <td>${stat.doctor_count}</td>
            <td>${stat.total_active_appointments}</td>
        </tr>
    `).join('');
}

// 新增：加载并渲染总体概览
async function fetchAndRenderOverallStats() {
    const response = await fetch('/api/dashboard/overall_stats/');
    const stats = await response.json();
    const ul = document.getElementById('overall-stats-list');
    ul.innerHTML = `
        <li class="list-group-item">总医生数量: ${stats.total_doctors}</li>
        <li class="list-group-item">总病人数量: ${stats.total_patients}</li>
        <li class="list-group-item">总预约数量: ${stats.total_appointments}</li>
        <li class="list-group-item">总处方数量: ${stats.total_prescriptions}</li>
        <li class="list-group-item">平均每个医生活跃预约数: ${stats.avg_active_appointments_per_doctor}</li>
    `;
}

// 处理添加医生
async function handleAddDoctor(e) {
    e.preventDefault();
    const docId = document.getElementById('doc-id').value;
    if (!/^doc/.test(docId)) {
        alert('请按要求输入：医生工号需以doc开头。');
        return;
    }
    const data = {
        id: docId,
        name: document.getElementById('doc-name').value,
        department_id: parseInt(document.getElementById('doc-dept').value),
        password: document.getElementById('doc-pass').value,
        title: document.getElementById('doc-title').value
    };
    const response = await fetch('/api/doctors/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    if (response.ok) {
        alert('医生添加成功！');
        e.target.reset();
        fetchAndRenderDoctors();
    } else {
        const error = await response.json();
        alert('添加失败: ' + error.detail);
    }
}

// 处理添加病人
async function handleAddPatient(e) {
    e.preventDefault();
    const patId = document.getElementById('pat-id').value;
    if (!/^pat/.test(patId)) {
        alert('请按要求输入：病历号需以pat开头。');
        return;
    }
    const data = {
        id: patId,
        name: document.getElementById('pat-name').value,
        gender: document.getElementById('pat-gender').value,
        password: document.getElementById('pat-pass').value,
        phone_number: document.getElementById('pat-phone').value
    };
    const response = await fetch('/api/patients/', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    });
    if (response.ok) {
        alert('病人添加成功！');
        e.target.reset();
        fetchAndRenderPatients();
    } else {
        const error = await response.json();
        alert('添加失败: ' + error.detail);
    }
}
</script>
</body>
</html>